import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
import { staticRoutes, allAsyncRoutes, anyRoute } from '@/router/routes'

// 引入接口
import { reqLogin, reqIofo, reqLoginOut } from '@/api/acl/login'
import router from '@/router';
import _ from 'lodash'

function filterRoutes(allAsyncRoutes: any, routes: any) {
  return allAsyncRoutes.filter((item: any) => {
    if (routes.indexOf(item.name) != -1) {
      if (item.children && item.children.length > 0) {
        item.children = filterRoutes(item.children, routes)
      }
      return true
    }
  })
}

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: []
  }),

  actions: {
    async login(username: string, password: string) {
      try {
        let result = await reqLogin({ username, password })
        // console.log(result);
        //  本地存储token
        this.token = result.token
        // 仓库存储
        setToken(result.token)
        return 'ok'
      } catch (error) {
        return Promise.reject('失败')
      }
    },

    async getInfo() {
      try {
        let result = await reqIofo()
        this.name = result.name
        this.avatar = result.avatar
        // 修改仓库里面menuRoutes的属性值   _.cloneDeep解决bug2
        let userRegisterAsyncRoute = filterRoutes(_.cloneDeep(allAsyncRoutes), result.routes)
        //动态添加路由
        this.setRouters([...userRegisterAsyncRoute, anyRoute])
        // 菜单显示
        this.menuRoutes = [...staticRoutes, ...userRegisterAsyncRoute]
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    },
    setRouters(registerRoute: any) {
      {
        registerRoute.forEach((item: any) => {
          router.addRoute(item)
        });
      }

    },
    async reset() {
      try {
        await reqLoginOut()
        // 删除local中保存的token
        removeToken()
        // 提交重置用户信息的mutation
        this.token = ''
        this.name = ''
        this.avatar = ''
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    },
  },
});
